#include "CodeConvert.h"
#include "Define.h"
using namespace std;

#ifdef _USE_WIN32
#else
#include <iconv.h>
static int _convert(const char *from, const char *to, char *dest, size_t destlen, char *src, size_t srclen)
{
	iconv_t cd = iconv_open( to, from );  
	if( cd == 0 )
	{
		return -1;  
	}
	memset( dest, 0, destlen );  
	if( iconv( cd, &src, &srclen, &dest, &destlen) == (size_t)-1 )
	{
		return -1;  
	}
	iconv_close(cd);  
	return 0;  
}
#endif


std::string gb2312_to_utf8(const std::string &str)
{
#ifdef _USE_WIN32
	int len = MultiByteToWideChar( CP_ACP, 0, str.c_str(), -1, NULL, 0 );
	wchar_t *wtext = (wchar_t*)malloc( (len+1) * sizeof(wchar_t) );
	if( !wtext ) return "";
	MultiByteToWideChar( CP_ACP, 0, str.c_str(), -1, wtext, len );
	len = WideCharToMultiByte( CP_UTF8, 0, wtext, -1, NULL, 0, NULL, NULL );
	char *text = (char*)malloc( (len+1) * sizeof(char) );
	if( !text ) return "";
	WideCharToMultiByte( CP_UTF8, 0, wtext, -1, text, len, NULL, NULL );
	free( wtext );
	string ret(text);
	free( text );
	return ret;
#else
	int len = (str.length() * 3 + 1) * sizeof(char);
	char *text = (char*)malloc( len );
	if( !text ) return "";
	if( _convert( "UTF-8", "GBK", text, len, (char*)str.c_str(), str.length() ) != 0 )
	{
		text[0] = 0;
	}
	string ret(text);
	free( text );
	return ret;
#endif
}

std::string utf8_to_gb2312(const std::string &str)
{
#ifdef _USE_WIN32
	int len = MultiByteToWideChar( CP_UTF8, 0, str.c_str(), -1, NULL, 0 );
	wchar_t *wtext = (wchar_t*)malloc( (len+1) * sizeof(wchar_t) );
	if( !wtext ) return "";
	len = MultiByteToWideChar( CP_UTF8, 0, str.c_str(), -1, wtext, len );
	len = WideCharToMultiByte( CP_ACP, 0, wtext, -1, NULL, 0, NULL, NULL );
	char *text = (char*)malloc( (len+1) * sizeof(char) );
	if( !text ) return "";
	len = WideCharToMultiByte( CP_ACP, 0, wtext, -1, text, len, NULL, NULL );
	free( wtext );
	string ret(text);
	free( text );
	return ret;
#else
	int len = (str.length()+1) * sizeof(char);
	char *text = (char*)malloc( len );
	if( !text ) return "";
	if( _convert( "GBK", "UTF-8", text, len, (char*)str.c_str(), str.length() ) != 0 )
	{
		text[0] = 0;
	}
	string ret(text);
	free( text );
	return ret;
#endif
}
